<template>
  <div v-loading="loading" class="top">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食谱名称" prop="name">
          <el-input :style="{ width: '200px' }" v-model="form.name" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="食谱编码" prop="code">
          <el-input :style="{ width: '200px' }" v-model="form.code" placeholder="请输入食谱编码" />
        </el-form-item>
        <el-form-item label="食谱图片" prop="code">
            <el-upload
              ref="upload"
              list-type="picture-card"
              :on-remove="handleRemove"
              :http-request="handleUploadFile"
              :file-list="form.cover"
              action="#"
              >
              <i class="el-icon-plus"></i>
            </el-upload>        
        </el-form-item> 
        <el-form-item label="食谱名称" prop="name">
          <el-input :style="{ width: '200px' }" v-model="form.name" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="三餐" prop="mealType">
            <el-select :style="{ width: '200px' }" v-model="form.mealType" placeholder="请选择" clearable>
                <el-option
                    v-for="item in dict.type.food_meals_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                </el-option>
            </el-select>       
        </el-form-item>        
        <el-form-item label="禁忌项" prop="symptomType">
            <el-select :style="{ width: '200px' }" v-model="form.symptomType" placeholder="请选择" clearable>
                <el-option
                    v-for="item in dict.type.food_meals_symptom"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                </el-option>
            </el-select>                     
        </el-form-item>      
        <el-form-item label="类型" prop="code">
            <!-- <el-input :style="{ width: '200px' }" v-model="form.tagType" :min-height="192"/> -->
            <el-select :style="{ width: '200px' }" v-model="form.tagType" placeholder="请选择" clearable>
                <el-option
                    v-for="item in dict.type.food_meals_tag"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                </el-option>
            </el-select>                    
        </el-form-item>  
        <el-form-item label="抗炎指数" prop="code">
            <el-input :style="{ width: '200px' }" v-model="form.antiInflammatory" :min-height="192"/>       
        </el-form-item>                     
        <el-form-item label="描述" prop="code">
            <el-input type="textarea" v-model="form.remark" :min-height="192"/>       
        </el-form-item>                 
        <el-form-item label="制作步骤" prop="code">
            <editor v-model="form.description" :min-height="192"/>       
        </el-form-item>         
          

        <el-form-item label="食物" prop="code">
            <el-button v-if="form.fctMealsSampleVOs.length === 0" class="btn"  @click="addMeal" type="primary">添加食物</el-button>

            <div v-for="(item,index) in form.fctMealsSampleVOs" :key="index">
                <el-select
                    :style="{ width: '200px' }"
                    v-model="form.fctMealsSampleVOs[index].sampleId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder=""
                    :remote-method="(query) => remoteMethodFront(query, item)"
                    @focus="remoteMethodFront(undefined, item)"
                    clearable
                    >
                    <el-option
                      v-for="item in sampleList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                            <span style="float: left">{{ item.name }}</span>
                 <img style="float: right; width: 30px; height: 30px;" v-if="item.cover.length>0" :src="'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + item.cover[0].url" />
                    </el-option>
                </el-select>
          <el-input class="inp-width" v-model="form.fctMealsSampleVOs[index].content" placeholder="重量" />
                  <el-select v-model="form.fctMealsSampleVOs[index].unitsId" placeholder="请选择">
                    <el-option
                    v-for="item in unitsList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>              
                <el-button class="btn"  @click="delMeal(index)" type="danger">删除</el-button>
                <el-button class="btn" v-if="index === form.fctMealsSampleVOs.length - 1 " @click="addMeal" type="primary">添加</el-button>
                

            </div> 
        </el-form-item>        

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="submit">确 定</el-button>
      </div>


  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/food/meals";
import { listSample} from "@/api/food/foodmanage";
import { listUnits } from "@/api/food/units";
import {
	put,
	getUrl,
} from '@/components/Upload/uploadOss.js'
import { listComposition} from "@/api/food/detail";

export default {
  dicts: ['food_meals_type', 'food_meals_tag', 'food_meals_symptom'],
  data() {
    return {
        id: '',
        fullCover: [],
        form: {
            fctMealsSampleVOs: [],
            cover: []
        },
        sampleList: [],
        rules: {
        },
        unitsList: [
        ],
        queryParams: {
            pageNum: 1,
            pageSize: 2000
        }, 
        loading: false             
    }
  },
  mounted(){
    this.form.id = this.$route.query.id
    this.loading = true;
    listUnits(this.queryParams).then(response => {
        this.unitsList = response.rows;
    });

    listSample(this.queryParams).then(response => {
        this.sampleList = response.rows;
        if(this.form.id){
            this.getDetail()
        }    
    this.loading = false;

    });   

    // console.log('static2222',this.unitsList);
  },
  methods: {
    cancel(){
      this.$router.push('/nutrition/meals')
    },

    handleRemove(file) {
      this.form.cover = this.form.cover.filter((item)=>(item.url) != file.url)
      console.log(this.form.cover);
    },

		handleUploadFile(option) {
				this.loading = true
				//获取上传后的url
				const _name = this.getDate() + '/' + option.file.uid + '.' + option.file.name.split('.')[1]
				put(_name, option.file).then((res) => {
					if (res) {
						getUrl(res.name).then((rel) => {
              console.log('static',rel);
							this.form.cover.push({
                url:'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + _name
              })
						})
					} else {
					}
            this.loading = false
				})
		}, 

    getDetail(){
      this.loading = true;
      getInfo(this.form.id).then(response => {
        this.form = response.data;
        this.form.fctMealsSampleVOs.forEach(element => {
          listComposition({
            pageNum: 1,
            pageSize: 2000,
            sampleId: element.sampleId
          }).then(list => {
            if(!this.form.antiInflammatory){
              this.form.antiInflammatory = Number(this.form.antiInflammatory) + Number(list.rows.find(obj => obj.compositionDetlId === '100002').content*0.18)
              - Number(list.rows.find(obj => obj.compositionDetlId === '700006').content*0.5 || 0)
              - (list.rows.find(obj => obj.compositionDetlId === '500007')?Number(list.rows.find(obj => obj.compositionDetlId === '500007').content*0.4):0)
              - (list.rows.find(obj => obj.compositionDetlId === '500010')?Number(list.rows.find(obj => obj.compositionDetlId === '500010').content*0.4):0);
              console.log('this.form.antiInflammatory',this.form.antiInflammatory);
            }
            this.form.antiInflammatory = this.form.antiInflammatory.toFixed(0)
          });
        });
        // this.form.fctMealsSampleVOs = this.form.fctMealsSampleVOs.map((item)=>({
        //     ...item,
        //     unitsId: unitsId.toString()
        // }))
        this.form.cover = this.form.cover.map(item => (
                {
                  ...item,
                  url: 'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + item.url
                }
          )
        )        
        this.loading = false;
      });        
    },
    remoteMethodFront(query, item) {
        if (query !== '') {
          listSample({
            name: query,
            pageNum: 1,
            pageSize: 2000,
            compositionId: item.compositionId || item.compositionDetlId
          }).then(response => {
              this.sampleList = response.rows;
            });

        } else {
          this.sampleList = [];
        }
      },
    remoteMethodBack(query) {
        if (query !== '') {
          listUnits({
            name: query,
            pageNum: 1,
            pageSize: 2000
          }).then(response => {
              this.unitsList = response.rows;
            });

        } else {
          this.unitsList = [];
        }
      }, 
    addMeal(){
        this.form.fctMealsSampleVOs.push({
            "mealsId": this.form.id,
            "sampleId": "",
            "content": "",
            "unitsId": ""
        })
    },
    delMeal(index){
        this.form.fctMealsSampleVOs.splice(index,1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
        this.form.cover = this.form.cover.map(item => (
                {
                  ...item,
                  url: this.toUrl(item.url)
                }
          )
        )            
          if (this.form.id != null) {
            console.log('static', this.form);
            this.form.fctMealsSampleVOs = this.form.fctMealsSampleVOs.filter(item => 
              item.unitsId !== '' || item.content !== '' || item.sampleId !== ''
            );
            console.log('static2222', this.form);
            updateInfo(this.form).then(response => {
              console.log('static',response);
              if(response.code === 200){
                this.$modal.msgSuccess("修改信息成功");
                // this.$router.push('/nutrition/meals')

              }
            });
          } else {
            delete this.form.
            addInfo(this.form).then(response => {

              this.$modal.msgSuccess("新增成功");
            });
          }
        }
      });
    },    
  }
}
</script>

<style scoped>
.top{
  margin-top: 50px;
}
.inp-width{
    width: 100px;
    margin: 0px 20px 10px 10px;
}
.btn{
    margin-left: 20px;
}
.dialog-footer{
    margin: 100px 0 100px 100px;
}
.submit{
  margin-left: 50px;
}
</style>